package com.freecloud.whispered.auth.controller;

import cn.hutool.core.util.StrUtil;
import com.freecloud.framework.annotation.CORS;
import com.freecloud.framework.annotation.SysLog;
import com.freecloud.framework.request.R;
import com.freecloud.whispered.auth.entity.SysUserEntity;
import com.freecloud.whispered.auth.service.SysUserService;
import com.freecloud.whispered.auth.service.SysUserTokenService;
import com.freecloud.whispered.auth.utils.ShiroUtils;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 登录相关
 * 
 * @author maomao
 * @email 138383877@qq.com
 */
@Api
@RestController
public class SysLoginController extends AbstractController{
	@Autowired
	private Producer producer;

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private SysUserTokenService sysUserTokenService;

	@ApiOperation(value = "验证码", notes = "生成随机验证码")
	@GetMapping("captcha.jpg")
	public void captcha(HttpServletResponse response)throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
		logger.info("setSession : {} -----{}",text,ShiroUtils.getSession().getId());
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
	}
	
	/**
	 * 登录
	 */
	@SysLog("登录系统")
	@ResponseBody
	@ApiOperation(value = "登录接口", notes = "后台用户登录接口")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "username" ,value = "用户账户",required = true,dataTypeClass = String.class,example = "admin"),
			@ApiImplicitParam(name = "password" ,value = "密码",required = true,dataTypeClass = String.class,example = "admin"),
			@ApiImplicitParam(name = "captcha" ,value = "验证码",required = true,dataTypeClass = String.class,example = "34343")
	})
	@RequestMapping(value = "/sys/login", method = RequestMethod.POST)
	public R login(String username, String password, String captcha){
		if(StrUtil.isBlank(username) || StrUtil.isBlank(password) || StrUtil.isBlank(captcha)){
			return R.error("必须参数不能为空！");
		}

		String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
		if(!captcha.equalsIgnoreCase(kaptcha)){
			logger.info("captcha : {} ------- kaptcha : {}",kaptcha);
			return R.error("验证码不正确");
		}

		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(username);
		if(user == null){
			logger.error("未找到账号为{}的账户！",username);
			return R.error("账号或密码不正确!");
		}

		Sha256Hash sha256Hash = StrUtil.isNotEmpty(user.getSalt()) ? new Sha256Hash(password, user.getSalt()) : new Sha256Hash(password);

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(sha256Hash.toHex())){
			return R.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0){
			return R.error("账号已被锁定,请联系管理员");
		}

		//生成token，并保存到数据库
		R r = sysUserTokenService.createToken(user.getUserId());
		return r;
	}
	
	/**
	 * 退出
	 */
	@ApiOperation(value = "退出", notes = "后台用户退出接口")
	@SysLog("退出系统")
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public R logout() {
		//ShiroUtils.logout();
		sysUserTokenService.logout(getUserId());
		return R.ok();
	}
	
}
